package com.morningstar.flow.flowable.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.morningstar.flow.antvX6.common.CopyTarget;
import com.morningstar.flow.service.FlowNodeCopyService;
import com.morningstar.flow.service.FlowNodeService;
import com.morningstar.system.api.feign.ISystemUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;

import java.util.HashSet;
import java.util.Set;

/**
 * 抄送审批任务
 */
@Slf4j
public class CopyServiceTask implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) {
        ExecutionEntityImpl entity = (ExecutionEntityImpl) execution;
        String activityId = entity.getActivityId();
        String processDefinitionKey = entity.getProcessDefinitionKey();
        FlowNodeService flowNodeService = SpringUtil.getBean(FlowNodeService.class);
        CopyTarget copyTarget = flowNodeService.getCopyTargetByDefinitionKey(processDefinitionKey, activityId);
        ISystemUserFeign systemUserFeign = SpringUtil.getBean(ISystemUserFeign.class);
        Set<Long> copyTargetUserIds = new HashSet<>();
        if (CollUtil.isNotEmpty(copyTarget.getUsers())) {
            copyTargetUserIds.addAll(systemUserFeign.selectUserByIds(copyTarget.getUsers()));
        }
        if (CollUtil.isNotEmpty(copyTarget.getRoles())) {
            copyTargetUserIds.addAll(systemUserFeign.selectUserByRoleIds(copyTarget.getRoles()));
        }
        if (CollUtil.isNotEmpty(copyTarget.getPosts())) {
            copyTargetUserIds.addAll(systemUserFeign.selectUserByPostIds(copyTarget.getPosts()));
        }
        if (CollUtil.isNotEmpty(copyTarget.getDepts())) {
            copyTargetUserIds.addAll(systemUserFeign.selectUserByDeptIds(copyTarget.getDepts()));
        }
        if (CollUtil.isNotEmpty(copyTarget.getDeptLeaders())) {
            copyTargetUserIds.addAll(systemUserFeign.selectUserByDeptLeaderIds(copyTarget.getDeptLeaders()));
        }
        log.info("CopyServiceTask {} {} {}", entity.getActivityName(), activityId, JSON.toJSON(copyTargetUserIds));
        if (CollUtil.isEmpty(copyTargetUserIds)) {
            return;
        }
        FlowNodeCopyService flowNodeCopyService = SpringUtil.getBean(FlowNodeCopyService.class);
        flowNodeCopyService.processCopy(copyTargetUserIds, entity);
    }
}
